package com.example.netty;

import com.example.netty.handler.NettyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

@Slf4j
public class HelloClient {

    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap()
                .group(group)
                // 客户端channel实现
                .channel(NioSocketChannel.class)
                // 添加该channel的处理器
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    // 连接建立后被调用
                    @Override
                    protected void initChannel(NioSocketChannel ch) {
                        ch.pipeline().addLast(new StringEncoder());
                        ch.pipeline().addLast(new NettyClientHandler());
                    }
                });
        log.info("客户端准备好了");

        // 阻塞直到连接到服务器
        ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress("localhost", 9010)).sync();

        // 使用监听器方式优雅退出，释放main线程
        channelFuture.channel().closeFuture().addListener((ChannelFutureListener) future -> {
            group.shutdownGracefully();
            log.info("客户端channel已关闭：{}", future.channel());
        });
    }

}
